<?php
require_once("../../class2.php");
require_once(HEADERF);
require_once("./includes/require_all.php");

function cleanse($value) {
	return htmlentities(stripslashes(strip_tags($value)));
}

$location= cleanse($_SERVER['PHP_SELF']);
$_GET['sby']= !isset($_GET['sby']) || $_GET['sby']==0 ? 1 : $_GET['sby'];
$addtoURL= "&sby=".$_GET['sby'];
$t_GETS= array("edit","cmpr","type","maxsize");
FOREACH ($t_GETS as $v) $addtoURL .= isset($_GET[$v]) ? "&".$v."=".cleanse($_GET[$v]) : "";

//--> Check if game is hidden
$tq= $db->prepare("SELECT game_show,PRIVATEGAME,id FROM admin_panel WHERE game_prefix=:PREF LIMIT 1	");
$tq->execute(array(':PREF'=>$CMS_pref));
$g_info= $tq->fetch(PDO::FETCH_ASSOC);

if($g_info["game_show"]){
	
	//Protection variables
	$game_private= $g_info["PRIVATEGAME"];
	$game_private_id= $g_info["id"];
	//Common variables
	$CMS_file= strip_tags($_GET['name']);
	$CMS_page= get_page();
	$CMS_pages= CMS_gamePagerInitiate();
	$offset= $page_rows*($CMS_page-1); //Offset for the pages
	//System functions
	CMS_dictionarySave();
	CMS_activitySave($location);

	//---> Load text arrays for translation
	$arrs= array(); $key=0;
	$txtarea_clr= array(
			 0=>array("[","]",":"," ","'",".","/","\\","&","#"),
			 1=>array("--IC001--","--IC002--","--IC003--","--IC004--","--IC005--","--IC006--","--IC007--","--IC008--","--IC009--","--IC010--"));
	$tq= $db->prepare("SELECT * FROM $text_table WHERE file_name=:FILE AND content<>'' LIMIT $page_rows OFFSET $offset");
	$tq->execute(array(':FILE'=>$CMS_file));
	foreach($tq->fetchAll(PDO::FETCH_ASSOC) as $nextrow){
		$arrs["id"][$key]= $nextrow['id'];
		$arrs["textid"][$key]= str_replace($txtarea_clr[0],$txtarea_clr[1],$nextrow['text_id']);
		$arrs["echoid"][$key]= $nextrow['text_id'];
		$arrs["translators"][$key]= $nextrow['translator'];
		$arrs["content"][$key]= $nextrow['content'];
		$arrs["bg"][$key]= cleanhtmlspecialchars(preg_replace("/\n/"," ",trim($nextrow['content'])));
		$arrs["en"][$key]= cleanhtmlspecialchars(preg_replace("/\n/"," ",trim($nextrow['english'])));
		$key++;
	} unset($key);

	//---> Record the posted translation
	if(isset($_POST['submit']) OR isset($_POST['appall'])){
		$temp = ''; //Temporary file for containing transformed text for user translation
		$strcount=0;
		foreach ($arrs["textid"] as $k => $w) {
			if($_POST['translation_'.$w] != "" and (preg_match("/([а-яА-Я]{1,}\s?[а-яА-Я]{1,})/u", $_POST['translation_'.$w]) or preg_match("/(_IGcoLLen)/", $w)) and !preg_match("/(<script)/", $_POST['translation_'.$w])){
				$strcount++;
				$tran = punctuation_check($_POST['translation_'.$w]);
				$temp .= (string)$arrs["echoid"][$k]."=>".$tran."\n";
			}
		}
		if(strlen($temp) > 0){
			$tq= $db->prepare("INSERT INTO $translations_table (translation, original, file_name, translator_id, translator_name, page) VALUES (:TEMP, :TEMP, :FILE, :UID, :UNAM, :PAGE)");
			$tq->execute(array(":TEMP"=>$temp,":FILE"=>$CMS_file,":PAGE"=>$CMS_page,":UID"=>USERID,":UNAM"=>USERNAME));
			CMS_statistic1SAVE($strcount);
			autosysmessage1($strcount, $game_private,$game_private_id);
			$tq= $db->prepare("UPDATE admin_panel SET pendingtranses = (SELECT count(*) FROM $translations_table WHERE status = 'В процес на проверка...') WHERE game_prefix=:PREF");
			$tq->execute(array(":PREF"=>$CMS_pref));
		}
		unset ($temp, $tran);
	}
	//---> Approve/Disapprove status or delete the translation
	if((isset($_POST['sbmtchck']) AND $_POST['sbmtchck']==true) OR isset($_POST['appall'])) {
		$tq= $db->prepare("SELECT id,translator_name FROM $translations_table WHERE page=:PAGE");
		$tq->execute(array(':PAGE'=>$CMS_page));
		$arr_ids= $tq->fetchAll(PDO::FETCH_ASSOC);
		FOREACH($arr_ids as $ent){
			$id_trans = $ent["id"];
			if(isset($_POST["approve_$id_trans"]) OR isset($_POST["r_trans_$id_trans"])){
				if(isset($_POST["approve_$id_trans"])) {
					$trans = $_POST["trans_$id_trans"];
				}
				elseif(isset($_POST["r_trans_$id_trans"])) {
					$trans = $_POST["r_trans_$id_trans"];
				}
				$tq= $db->prepare("UPDATE $translations_table SET status='Одобрен', translation=:TRANS WHERE id=:ID AND file_name=:FILE");
				$tq->execute(array(':FILE'=>$CMS_file,':TRANS'=>$trans,':ID'=>$id_trans));
				$count=0;
				$translator= $ent['translator_name'];
				$translation = explode("\n", $trans);
				foreach($translation as $appornot){
					if(preg_match('/[А-я]{2}/',$appornot)) $count++;
				}
				$codes = array(); //It will contain codes from user's translation
				foreach($translation as $v){
					$g = explode("=>", $v);
					$codes[] = $g[0];
				}
				foreach($codes as $key => $code){
					$code_repl= 0;
					$t = explode("=>", $translation[$key]);
					if (preg_match("/(_IGcoLLen)/", $code)) $code_repl= str_replace("_IGcoLLen", "", $code);
					if (preg_match("/(IC101: Остави английския текст)/", $t[1])) {  // Сменяме text_id-то на файла, за да бъде считан низът оттук-нататък като преведен
						$t[1]= str_replace ("(IC101: Остави английския текст)", "", $t[1]);
						if ($code_repl!==0) {$code_repl.= "_IGcoLLen";};
						if ($code_repl===0) {$code_repl= $code."_IGcoLLen";};
					}
					if ($code_repl!==0) {
						$tq= $db->prepare("UPDATE $text_table SET text_id = replace(text_id, :CODE, :REPL) WHERE text_id = :CODE AND file_name = :FILE");
						$tq->execute(array(':FILE'=>$CMS_file,':CODE'=>$code,':REPL'=>$code_repl));
						$code= $code_repl;
					}
					$s= array_search($code, $arrs["echoid"]);
					$acting_translator= $s && $arrs["translators"][$s]!="original" ? $arrs["translators"][$s] : $translator;
					$tq= $db->prepare("UPDATE $text_table SET content=:BG, translator=:ATOR WHERE text_id=:CODE AND file_name=:FILE");
					$tq->execute(array(':FILE'=>$CMS_file,':CODE'=>$code,':ATOR'=>$translator,':BG'=>$t[1]));
				
					//translating all the same rows
					$x = mysql_query("select * from $text_table where text_id = '$code' and file_name = '".mysql_real_escape_string($CMS_file)."'");
					$y = mysql_fetch_array($x);
					$id = $y['text_id'];
					$eng = $y['english'];
					$bg = $y['content'];
					$tr = $y['translator'];
					$rrr = mysql_query("select * from $text_table where english = binary '".mysql_real_escape_string($eng)."'");
					if(mysql_num_rows($rrr)){
						if(preg_match("/(_IGcoLLen)/", $id)){
							mysql_query("UPDATE $text_table SET text_id = concat(text_id, '_IGcoLLen'), content = '".mysql_real_escape_string($bg)."', translator = '".mysql_real_escape_string($tr)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator = 'original'");
							mysql_query("UPDATE $text_table SET text_id = concat(text_id, '_IGcoLLen'), content = '".mysql_real_escape_string($bg)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator != 'original'");
						}
						else{
							mysql_query("UPDATE $text_table SET content = '".mysql_real_escape_string($bg)."', translator = '".mysql_real_escape_string($tr)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator = 'original'");
							mysql_query("UPDATE $text_table SET content = '".mysql_real_escape_string($bg)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator != 'original'");
						}
					}
				}
				CMS_lastApprovedSave($count, $translator);
				$tq= $db->prepare("UPDATE admin_panel SET wordsall = (SELECT SUM( LENGTH(english) - LENGTH(REPLACE (english, ' ', ''))+1) FROM $text_table), wordsdone = (SELECT SUM( LENGTH(english) - LENGTH(REPLACE (english, ' ', ''))+1) FROM $text_table WHERE content!=english OR translator!='original' OR content REGEXP '[а-яА-Я ]{10}') WHERE game_prefix=:PREF");
				$tq->execute(array(":PREF"=>$CMS_pref));
				autosysmessage2($count, $translator, $id_trans, $_GET['game'], $game_private,$game_private_id);
				
				if($_POST['submit']=="Одобрявай" AND !isset($dontcopymytwice)){
					$temp = ''; //Temporary file for containing transformed text for user translation
					$strcount=0;
					foreach ($arrs["textid"] as $k => $w) {
						if($_POST['translation_'.$w] != "" and (preg_match("/([а-яА-Я]{1,}\s?[а-яА-Я]{1,})/u", $_POST['translation_'.$w]) or preg_match("/(_IGcoLLen)/", $w)) and !preg_match("/(<script)/", $_POST['translation_'.$w])){
							$strcount++;
							$tran = punctuation_check($_POST['translation_'.$w]);
							$temp .= (string)$arrs["echoid"][$k]."=>".$tran."\n";
						}
					}
					if(strlen($temp) > 0){
						$tq= $db->prepare("INSERT INTO $translations_table (translation, original, file_name, translator_id, translator_name, page) VALUES (:TEMP, :TEMP, :FILE, ".USERID.", ".USERNAME.", :PAGE)");
						$dontcopymytwice= true;
						$tq->execute(array(":TEMP"=>$temp,":FILE"=>$CMS_file,":PAGE"=>$CMS_page));
						CMS_statistic1SAVE($strcount);
						autosysmessage1($strcount, $game_private,$game_private_id);
					}
					unset ($temp, $tran);
				}
			}
			elseif(isset($_POST["change_$id_trans"])){
				$trans = $_POST["trans_$id_trans"];
				$td= $db->prepare("UPDATE $translations_table SET translation=:TRANS WHERE id=:ID AND file_name=:FILE");
				$td->execute(array(":TRANS"=>$trans,":ID"=>$id_trans,":FILE"=>$CMS_file));
				$td= $db->prepare("SELECT translator_name FROM $translations_table WHERE id=:ID LIMIT 1");
				$td->execute(array(":ID"=>$id_trans));
				$tmp= $td->fetch(); $translator= $tmp["translator_name"];
				$translation = explode("\n", $trans);
				$count= count($translation);
				autosysmessage3($count, $translator, $id_trans, $_GET['game'], $game_private,$game_private_id);
			}
			elseif(isset($_POST["disapprove_$id_trans"])){
				$td= $db->prepare("SELECT translator_name FROM $translations_table WHERE id=:ID LIMIT 1");
				$td->execute(array(":ID"=>$id_trans));
				$tmp= $td->fetch(); $translator= $tmp["translator_name"];
				$td= $db->prepare("UPDATE $translations_table SET status = 'Неодобрен' WHERE id=:ID");
				$td->execute(array(":ID"=>$id_trans));
				autosysmessage4($translator, $id_trans, $_GET['game'], $game_private,$game_private_id);
			}
			elseif(isset($_POST['delete_'.$id_trans])){
				$tq= $db->prepare("DELETE FROM $translations_table WHERE id=:ID");
				$tq->execute(array(":ID"=>$id_trans));
				autosysmessage5($_GET['game'], $game_private,$game_private_id);
			}
			elseif(isset($_POST["split_$id_trans"])){
				$trans = $_POST["trans_$id_trans"];
				$translation = explode("\n", $trans);
				$n=0;
				while (isset($_POST["ord_{$id_trans}_{$n}"])&&$_POST["ord_{$id_trans}_{$n}"]>0) {
					$array_assorte[$_POST["ord_{$id_trans}_{$n}"]][]= $translation[$n];
					$n++;
				}
				$td= $db->prepare("SELECT * FROM $translations_table WHERE id=:ID LIMIT 1");
				$td->execute(array(":ID"=>$id_trans));
				$old= $td->fetch();			
				foreach ($array_assorte as $r) {
					$trans= str_replace("\n\n", "\n", implode("\n",$r));
					$tq= $db->prepare("INSERT INTO $translations_table (translation, original, file_name, status, time, translator_id, translator_name, page) VALUES (:TRANS, :OLD, :FILE, '$old[status]', '$old[time]', '$old[translator_id]', '$old[translator_name]', '$old[page]')");
					$tq->execute(array(":TRANS"=>$trans, ":OLD"=>$old[original], ":FILE"=>$old[file_name]));
				}
				$tq= $db->prepare("DELETE FROM $translations_table WHERE id=:ID");
				$tq->execute(array(":ID"=>$id_trans));
			}
		}
		$tq= $db->prepare("UPDATE admin_panel SET pendingtranses = (SELECT count(*) FROM $translations_table WHERE status = 'В процес на проверка...') WHERE game_prefix=:PREF");
		$tq->execute(array(":PREF"=>$CMS_pref));
		header("Location: $location?game=$CMS_game&name=$CMS_file&page=$CMS_page&go=pending$addtoURL#$id_trans");
	} else {
		//---> Chat Open
		if(in_array(USERNAME,$adminss) OR in_array(USERNAME,$additionaltoadmins) OR in_array(USERNAME,$trainees)){
			ramka("open","Вътрешен чат");
			include("chats/index.php");
			ramka("close");
			echo "<div style='min-height:25px'></div>";
		}
		
		ramka("open","Текст на играта за превод");
		
		//---> Load translated ids for for yellow, green and red markings
		$tq= $db->prepare("SELECT id,translation,translator_name FROM $translations_table WHERE file_name=:FILE AND page=:PAGE and status='В процес на проверка...'");
		$tq->execute(array(":FILE"=>$CMS_file,":PAGE"=>$CMS_page));
		foreach($tq->fetchAll(PDO::FETCH_ASSOC) as $nextrow){
			if($nextrow['translation'] != ''){
				$temp = explode("\n", trim($nextrow['translation'])); //Dividing user's translation into rows
				$rows_in_thistranslation= count($temp); 
				foreach($temp as $k=>$v){
					$part = explode("=>", $v);
					isset($part[1]) || $part[1]=""; $part[1] = cleanhtmlspecialchars($part[1]);
					$arr_transids[] = $part[0];
					$arr_transes[] = $part[1];
					$arr_transons[] = $nextrow['translator_name'];
					$arr_transinputcodes[]=<<<WAITING_APPROVAL_TEXTAREA
						<div style='margin-bottom:5px;'>
							<textarea id='r_$nextrow[id]{$k}_t' name='r_$nextrow[id]{$k}_t' class='expand tbox borderGREY TBOX2' style='width:96%; margin:0px; color:yellow;' onChange='approve_shananigans_exec("$nextrow[id]","r_$nextrow[id]{$k}_t","r_$nextrow[id]$k","$rows_in_thistranslation");' onKeyUp='approve_shananigans_exec("$nextrow[id]","r_$nextrow[id]{$k}_t","r_$nextrow[id]$k","$rows_in_thistranslation");'>$part[1]</textarea>
							<div style='float:right;'>
								<span class='button textRED' onClick='clearTextArea("r_{$nextrow['id']}{$k}");populateTextArea("UFORM_{$nextrow['id']}","r_{$nextrow['id']}","trans_{$nextrow['id']}");' style='vertical-align:middle;'>X</span>
							</div>
						</div>
WAITING_APPROVAL_TEXTAREA;
					$arr_transsumids[$nextrow['id']]=trim($nextrow['translation']);
				}
			}
		}
		unset ($rowss, $nextrow, $temp, $v, $part);

		require_once("viewtext-topmenu.php");
		$t_delimiters= array("<"=>">","["=>"]","{"=>"}");
		$t_delimiters_special= array("BioShockInfinite"=>array("("=>")"));
		$t_special_regexes= array("BioShockInfinite"=>array(0=>'/("|&quot;)(.*?)("|&quot;)/',1=>"$1<span class='trlat'>$2</span>$3"));
		if(isset($t_delimiters_special[$CMS_game])) $t_delimiters= array_merge($t_delimiters,$t_delimiters_special[$CMS_game]);
		foreach($arrs["en"] as $key => $val) {
			$val= htmlspecialchars_decode($val);
			$charlenght= strlen($val); $a=0; $c=0; $t_val=array(); $t_opened= false; $t_opened2= false; $t_delimiter= ""; 
			while ($c<$charlenght) {
				$letter= $val[$c]; $c++;
				if (array_key_exists($letter,$t_delimiters)&&$t_opened==false) {
					if ($t_opened2==true) {
						$t_opened2= false;
						$a++;
					}
					$t_val[$a]["str"]= $letter;
					$t_val[$a]["stat"]= 0;
					$t_opened= true;
					$t_delimiter= $t_delimiters[$letter];
				} elseif ($t_delimiter!=""&&$letter==$t_delimiter) {
					$t_val[$a]["str"].=$letter;
					$a++;
					$t_opened= false;
					$t_delimiter= "";
				} elseif ($t_opened==true) {
					$t_val[$a]["str"].=$letter;
				} elseif ($t_opened==false&&$t_opened2==false) {
					$t_val[$a]["str"]= $letter;
					$t_val[$a]["stat"]= 1;
					$t_opened2= true;
				} elseif ($t_opened2==true) {
					$t_val[$a]["str"].=$letter;
				}
			}
			$t_val_end="";
			foreach ($t_val as $substr) {
				$substrclass= $substr["stat"]==0 ? "trcode" : "trlat";
				$substrtext = cleanhtmlspecialchars($substr["str"]);
				if(isset($t_special_regexes[$CMS_game])) $substrtext= preg_replace($t_special_regexes[$CMS_game][0],$t_special_regexes[$CMS_game][1],$substrtext);
				//if (USERNAME=="Mnementh" AND $substr["stat"]==1) $substrtext= preg_replace('/([@#\$%\&]{1,10}[A-z0-9_@#\$%\&;:]{1,100})/','<span class="trcode">$1</span>',$substrtext);
				$t_val_end.= "<span class='$substrclass'>$substrtext</span>";
			}
			$arrs["en2"][$key]= $t_val_end;
		}			
		$dict= CMS_dictionaryLoad();
		$arr_bg2= CMS_insertDictTooltips($dict, $arrs["en2"]);
		unset($arrs["en2"]);

		//---> Loading users from history
		$tq= $db->prepare("SELECT user_name FROM cms_actusers WHERE date > NOW() - interval 20 minute AND location_present LIKE :FIND AND user_name!='USERNAME'");
		$getpart= "game=".strip_tags($_GET['game'])."&name=".strip_tags($_GET['name'])."&page=".strip_tags($_GET['page']);
		$tq->execute(array(":FIND"=>"%$getpart%"));
		
		foreach($tq->fetchAll(PDO::FETCH_ASSOC) as $useron){
			$usersonpage[]= "<span class='forumheader' style='background:none;'>$useron[user_name]</span>";
		}
		$usersimplode= implode(", ",$usersonpage);
		if(USERNAME!="USERNAME") echo "<div style='padding:0px 5px 0px 5px;'><b>На тази страница:</b> {$usersimplode}</div>";
		
		if(isset($strcount) AND $strcount>0) echo "<center class='cmsMessage' style='padding-top:4px;'><span class='textRED' style='font-size:24px;'>✉</span> <b style='vertical-align:top;'>Репликите бяха запазени. Благодарим ви! </b></center>";
		CMS_lastApprovedEcho();
		if(USERNAME=="USERNAME") echo "<br>";
		echo <<<EMPTY_TOOLTIP_DECLARATION
				<div class='forumheader4'>
					<div id='enbgwordFOUND'></div>
					<div id='searchFOUND'></div>
EMPTY_TOOLTIP_DECLARATION;

		//---> Show form for acquiring translations
		if($user_rights["ADD"]===1 && USERNAME!='USERNAME'){
			if ($user_rights["APPROVE"]===1) {
				$tq= $db->prepare("SELECT count(status) as cnt FROM cms_dict WHERE game=:GAME AND status=0");
				$tq->execute(array(":GAME"=>$CMS_game)); 
				$tmp= $tq->fetch();
				if ($tmp[0]>0) echo <<<WORDS_WAITING_APPROVAL
					<div class='forumheader'>
						<b>В игровия речник чакат одобрение думи: </b> <a href='dict.php#$CMS_game' class='button'>$tmp[cnt]</a>
					</div>
WORDS_WAITING_APPROVAL;
			}
			$text = ''; //It will contain the untranslated text for the edittext.php // Not sure if still needed
			echo <<<NEW_TRANSLATION_FORM_OPEN
					<form action='' method='post' style='display: inline;'>
						<div onmouseup='parseselection()'>
							<TABLE CELLSPACING='0' CELLPADDING ='4' WIDTH='100%'>
NEW_TRANSLATION_FORM_OPEN;
			$rowcolors= array("green"=>0,"yellow"=>0,"red"=>0);
			foreach ($arrs["echoid"] as $key => $value) {
				$text_id= $value;
				$content= cleanhtmlspecialchars($arrs["bg"][$key]);
				$content2= $arrs["en"][$key];
				$content_slashed= $arrs["en"][$key];
				$translator= $arrs["translators"][$key];
				$content_tooltiped= $arr_bg2[$key];
				$textarea= $arrs["textid"][$key];
				$show_maxsize= isset($_GET["maxsize"]) ? (strlen($content2)<=$_GET["maxsize"] ? true : false) : true;
				$show_type= isset($_GET["type"]) ? $_GET["type"] : 0;
		//---------------------------------- //Checks for similar strings translated in other games
				if (isset($_GET['cmpr']) AND in_array(USERNAME,$gods)) {
					$r_bds= preg_match("/\|/",$_GET['cmpr']) ? explode("|",$_GET['cmpr']) : array($_GET['cmpr']);
					if (isset($recemplate)) unset($recemplate);
					FOREACH($r_bds as $r_bd){
						$r_bd= cleanse($r_bd)."_text";
						$tq= $db->prepare("SELECT content FROM $r_bd WHERE english=:FIND");
						$tq->execute(array(":FIND"=>$content2));
						FOREACH ($tq->fetchAll(PDO::FETCH_ASSOC) as $a){
							$recemplate[]= $a['content'];
						}
					}
				}
		//----------------------------------			
				$ttxt=""; $ttxt2="";
				if (isset($arr_transids) AND in_array($text_id, $arr_transids)) { 
					foreach($arr_transids as $tk=>$tv) {
						if($tv==$text_id and $arr_transes["$tk"]!="") {
							$ttxt.= <<<USER_SEE_SENT_ROW_TRANSLATIONS
									<span class='textYELLOW unselectable'>$arr_transes[$tk]</span>
									<span class='unselectable textWHITE defcursor' style='font-size:10px; margin-top:-5px; margin-left:10px;'>$arr_transons[$tk]</span><br>
USER_SEE_SENT_ROW_TRANSLATIONS;
							$ttxt2.= $arr_transinputcodes["$tk"];
						}
					}
				}
				if($user_rights["APPROVE"]===1) $ttxt=$ttxt2;
				if(preg_match("/([а-яА-Я]{1,}\s?[а-яА-Я]{1,})/u", $content) OR preg_match("/(_IGcoLLen){1}/", $text_id)){
					$rowcolors["green"]++;
					$charcount= strlen($arr_bg2[$key]);
					$arr_temp_green[]= $text_id;
		if($show_maxsize&&$show_type<1){
					echo <<<OPENING_GREEN_ROW
							<tr style='font-size:14px;' id='row_$textarea'>
								<td style="vertical-align:top;" WIDTH="2%" class='forumheader3 unselectable'>
									<span class='textGREEN' title='Репликата е преведена и одобрена.' style='cursor:help; float:right;'>✔</span>
								</td>
OPENING_GREEN_ROW;
					if($user_rights["APPROVE"]===1 AND (isset($_GET["cmpr"]) OR isset($_GET["edit"]))) {
						$java_content= preg_match("/(_IGcoLLen){1}/", $text_id) ? "(IC101: Остави английския текст)" : "";
						$java_content= cleanhtmlspecialchars($java_content);
						echo <<<GREEN_ROW_SECOND_MODE
								<td WIDTH="68%" class="forumheader3" style="vertical-align:top;">
									<span>$content</span>
									<br>
									<span class="textRED" style="font-weight:normal;">$content_tooltiped</span>
								</td>
								<td WIDTH="30%" class="forumheader3" style="vertical-align:top;">
								<div id='autoinsertin_trans_$textarea' style='display:none;'>$java_content</div>
								<textarea name="translation_$textarea" id="trans_$textarea" 
											onkeyup="countTextchars(this, '#chars_$textarea', '$charcount')"
											onfocus="countTextchars(this, '#chars_$textarea', '$charcount')"
											onblur="toggleSpan('chars_$textarea', '');"
											onclick="javascript:autoInsert2('trans_$textarea', 'autoinsertin_trans_$textarea');"
											style="border-radius: 1px; margin-top:-1px; width: 100%"
											class="expand tbox TBOX2"></textarea>
								<div style='font-size:10px; margin-top:-5px;'>
									<span class='textGREEN'>[$text_id]</span>
									<span id='chars_$textarea' style='margin-top:-5px; cursor:help;' title='Информативно съотношение на\nпреведения текст спрямо оригинала.\nСпазването му не е задължително.'></span>
									<span style='font-size:10px; margin-top:-5px;' class='unselectable textGREY defcursor'> &nbsp; $translator </span>
								</div>
GREEN_ROW_SECOND_MODE;
					} else {
						isset($addxxx) || $addxxx=""; isset($addxxx2) || $addxxx2="";
						$java_content= preg_match("/(_IGcoLLen){1}/", $text_id) ? $content."(IC101: Остави английския текст)" : $content;
						$java_content= cleanhtmlspecialchars($java_content);
						$bold_content= preg_replace('/([0-9 ]{0,100}[А-я]{1,1000}[А-я0-9 \.!\?,-]{0,1000})/u','<span class="trcyr">$1</span>',$content);
						echo <<<GREEN_ROW_MAIN
								<td class="forumheader3"  style="vertical-align:top;" align='left'>
									<div class='translationrow-header' style='font-weight:normal;cursor:pointer;' onclick=toggleBLOC('toggleText_$textarea')>
										<span class='unselectable' unselectable="on" oncopy="return false" oncut="return false" title='Нов превод'>$bold_content</span>
										<span style="font-size:10px; margin-top:-5px;" class="unselectable textWHITE defcursor"> &nbsp; $translator</span>$ttxt
									</div>
									<div id="toggleText_$textarea" style='display:none;'>
										<div class="translationrow-subheader textRED">
											<div>$content_tooltiped</div>
											<div id='autoinsertin_trans_$textarea' style='display:none;'>$java_content</div>
											<textarea name="translation_$textarea" id="trans_$textarea" 
												oncopy="return false" oncut="return false"
												onkeyup="countTextchars(this, '#chars_$textarea', '$charcount')"
												onfocus="showBLOC('rh_$textarea');countTextchars(this,'#chars_$textarea','$charcount')"
												onblur="hideBLOC('rh_$textarea')"
												onclick="autoInsert2('trans_$textarea', 'autoinsertin_trans_$textarea');"
												style="border-radius: 1px; padding: 0px; margin-left: -2px; width: 99%"
												class="expand tbox TBOX2"></textarea>
											<div style='margin-top:-5px;display:none;' id='rh_$textarea' class='textGREY'>
												<span id="main_$textarea" class="textGREEN" style="font-size:10px; cursor:help;" title="Идентификатор на репликата\nМоже да съдържа важна информация за говорещия, ситуацията и т.н.">[$text_id]</span>  
												<span id='chars_$textarea' style='margin-top:-5px; font-size:10px; cursor:help;' title='Информативно съотношение на\nпреведения текст спрямо оригинала.\nСпазването му не е задължително.'></span>
												$addxxx $addxxx2
											</div>
										</div>
									</div>
GREEN_ROW_MAIN;
					}
					echo <<<CLOSING_THE_ROW
								</td>
							</tr>
CLOSING_THE_ROW;
		}
				} else {
					$charcount= strlen($arrs["bg"][$key]);
					if (isset($arr_transids) AND in_array($text_id, $arr_transids)) { 
						$icon= "✉"; $color= "YELLOW"; $titled="Има чакащ одобрение превод..."; $rowcolors["yellow"]++;
					} else {
						$icon= "✘"; $color= "RED"; $titled="Репликата все още не е превеждана."; $rowcolors["red"]++;
					}
					$text.= $text_id."=".$content."\n";
		if($show_maxsize){
					echo <<<OPENING_RED_OR_YELLOW_ROW
							<tr style='font-size:14px;'>
								<td style="vertical-align:top;" WIDTH="2%" class='forumheader3 unselectable'>
									<span class='text$color' title='$titled' style='cursor:help;'>$icon</span>
								</td>
OPENING_RED_OR_YELLOW_ROW;
					if($user_rights["APPROVE"]===1 AND (isset($_GET["cmpr"]) OR isset($_GET["edit"]))) {
					
						echo <<<ALTERNATIVE_MODE
								<td class="forumheader3" WIDTH="68%" style="vertical-align:top;">
									$content_tooltiped<br>$ttxt
ALTERNATIVE_MODE;
						IF (isset($recemplate[0])) {
							FOREACH ($recemplate as $a) { echo "<div class='textWHITE'>$a<div>"; }
							$filler= trim($recemplate[0]);
						} ELSE $filler="";
						$filler = cleanhtmlspecialchars($filler);
						isset($addxxx) || $addxxx=""; isset($addxxx2) || $addxxx2="";
						echo <<<ALTERNATIVE_MODE
								</td>
								<td class="forumheader3" WIDTH="30%" style="vertical-align:top;">
									<textarea name="translation_$textarea" rows="1" id="trans_$textarea" 
											style="border-radius: 1px; margin-top:-1px; margin-bottom:5px; width:82%;"
											class="expand tbox borderGREY TBOX2"
											onkeyup="countTextchars(this, '#chars_$textarea', '$charcount')"
											onfocus="showBLOC('rh_$textarea');countTextchars(this,'#chars_$textarea','$charcount')"
											onblur="hideBLOC('rh_$textarea')">$filler</textarea>
									<span id="unneeded" class="unselectable"> </span>
ALTERNATIVE_MODE;

					} else {
						
						foreach ($dict as $w) {
							$w= trim($w['word']);
							$preg_apend= $preg_apend."|".ucfirst($w);
							$w{0} = strtolower($w{0});
							$preg_apend.= "|".$w;
						}
						preg_match_all("/\\\\&(amp;|quot;|#039;|lt;|gt;|'|\")|\\[n]{0,1}|[^A-z&]{0,100}((<|&lt;|&amp;lt;)(.*?)(>|&gt;|&amp;gt;)|\((.*?)\)|\[(.*?)\]|\{(.*?)\}|%[^ %]{0,100}|[^ ]{0,100}%".$preg_apend.")[^A-z%\(\)\[\]\{\}<>&]{0,100}|[0-9 \.,-:$%]{4,100}|[*\(\)\[\]\{\}<>]{0,100}/",$content,$ingamecodestaken, PREG_PATTERN_ORDER);
						$ingamecodes=cleanhtmlspecialchars(implode("",$ingamecodestaken[0]));
						foreach ($dict as $w) {
							$w1= trim($w['word']);
							$w2= trim($w['translation']); preg_match("/<b>(.*?)<\/b>/", $w2, $w2_t); $w2= $w2_t[1];
							$w1= ucfirst($w1);
							$w2= mb_convert_case($w2, MB_CASE_TITLE, "UTF-8");
							$w1s[]=$w1; $w2s[]=$w2;
							$w1[0]= strtolower($w1[0]);
							$w2= mb_convert_case($w2, MB_CASE_LOWER, "UTF-8");
							$w1s[]=$w1; $w2s[]=$w2;
							$ingamecodes= str_replace($w1s,$w2s,$ingamecodes);
						}
						echo <<<RED_OR_YELLOW_ROW_MAIN
								<td class="forumheader3" align="justify" style="vertical-align:top;">
									<div class='translationrow2-header'>$content_tooltiped</div>$ttxt
									<div id='autoinsertin_trans_$textarea' style='display:none;'>$ingamecodes</div>
									<div id='autoinsertoriginalin_trans_$textarea' style='display:none;'>$content</div>
									<textarea name="translation_$textarea" rows="1" id="trans_$textarea" 
											style="border-radius: 1px; padding: 0px; margin-left: 4px; width: 94%"
											class="expand tbox borderGREY TBOX2"
											onkeyup="countTextchars(this, '#chars_$textarea', '$charcount')"
											onfocus="showBLOC('rh_$textarea');countTextchars(this,'#chars_$textarea','$charcount');
											autoInsert2('trans_$textarea','autoinsertin_trans_$textarea');"
											onblur="hideBLOC('rh_$textarea')"></textarea>
									<span id="unneeded" class="unselectable"> </span>
RED_OR_YELLOW_ROW_MAIN;

}
						echo <<<RED_OR_YELLOW_ROW_MAIN
									<span style='cursor: pointer; vertical-align:top;' alt="Добави" title='Остави на английски' class="unselectable button textWHITE" style="margin-top:-15px;"
									onClick="autoInsert2('trans_$textarea','autoinsertoriginalin_trans_$textarea','(IC101: Остави английския текст)');">EN</span>
									<br>
									<div style='margin-top:-5px;display:none;' id='rh_$textarea'>
										<span id="main_$textarea" class="text$color" style="font-size: 10px; cursor:help;" title="Идентификатор на репликата\nМоже да съдържа важна информация за говорещия, ситуацията и т.н.">[$text_id]</span>  
										<span id='chars_$textarea' style='margin-top:-5px; font-size: 10px; cursor:help;' title='Информативно съотношение на\nпреведения текст спрямо оригинала.\nСпазването му не е задължително.'></span>
										$addxxx $addxxx2
									</div>
								</td>
							</tr>
RED_OR_YELLOW_ROW_MAIN;

				}
			}
			$aditional_buttons=""; $hidden_fields="";
			if ($user_rights["APPROVE"]===1) {
				$ahref= "$location?game=$CMS_game&name=$CMS_file&page=$CMS_page&$addtoURL";
				if (!isset($_GET['edit'])) {
					$atext = "Редакция";
					$ahref.= "&edit=true";
				} else {
					$atext = "Стандартно";
					$ahref = str_replace("&edit=true","",$ahref);
				}
				$aditional_buttons.= "<a href='$ahref' class='unselectable button textRED' style='font-weight:normal;'>$atext</a>";
				if(count($arr_transes)>0) $aditional_buttons.= "<input name='appall' type='submit' value='Одобрявай' class='button textGREEN' id='masssend-trans'>";
				FOREACH($arr_transsumids as $untrans=>$transtext) {
					$transtext= cleanhtmlspecialchars($transtext);
					$hidden_fields.= "<textarea name='r_trans_$untrans' id='r_trans_$untrans' class='expand tbox borderGREY TBOX2' style='width:99%;opacity:0.4;display:none;'>$transtext</textarea>";
				}
			}
			
			$rc=$rowcolors["red"]; $yc=$rowcolors["yellow"]; $gc=$rowcolors["green"]; 
			if($yc==0 AND $gc==0) { $qcolor= "red"; }
			elseif($rc==0 AND $yc==0) { $qcolor= "green"; }
			elseif(($yc+$gc)<$rc) { $qcolor= "orange"; }
			elseif(($yc+$gc)>$rc) {
				if($rc==0) $qcolor= "green2";
				else $qcolor= "yellow";
			}
			$insert= "$CMS_game??$CMS_file??$CMS_page";
			mysql_query("INSERT INTO cms_overalpages (page, status) VALUES ('".mysql_real_escape_string($insert)."', '$qcolor') ON DUPLICATE KEY UPDATE status='$qcolor'");
		}			
			echo <<<CLOSING_USER_FORM
							</TABLE>
						</div><br>
					</div>
					<div class="forumheader" style="font-weight:normal;">
						<center class="unselectable" style="margin-top:-15px;">
							<input name="submit" type="submit" value="Изпрати" class="button" id="send-trans">
							$aditional_buttons
							$hidden_fields
						</center>
					</div>
				</form>
				<br>
CLOSING_USER_FORM;
		
	//---> Alpha-pager (Previous|Present|Next)		
			$p_prev=$CMS_page-1; $p_next=$CMS_page+1;
			if ($CMS_pages>1)
			{
				echo '<center class="unselectable" style="margin-top:-10px;">';
				if ($p_prev>0 AND $p_prev<=$CMS_pages) {
					echo "<a id='prev-page' href='$location?game=$CMS_game&name=$CMS_file&page=$p_prev&$addtoURL' style='font-size:24px; vertical-align:bottom;'>◄</a>"; }
				echo "<a class='button textWHITE defcursor' style='font-size:14px;cursor:help;' title='Настояща страница'><b>$CMS_page</b></a>";
				if ($p_next>0 AND $p_next<=$CMS_pages) {
					echo "<a id='next-page' href='$location?game=$CMS_game&name=$CMS_file&page=$p_next&$addtoURL' style='font-size:24px; vertical-align:bottom;'>►</a>"; }	
				echo "</center>";
				echo '<br>';
			}
			
	//---> Counting the comments
			$tq= $db->prepare("SELECT COUNT(*) as cnt FROM cms_notes WHERE game=:GAME AND status='Видимо'");
			$tq->execute(array(":GAME"=>$CMS_game));
			$tmp= $tq->fetch();
			$num_notes= $tmp["cnt"];

	//---------------------------- SECOND MENU START ------------------------------------
	?>
				<div class="forumheader4">
					<center style='margin-top:-16px;'>
						<table class="forumheader4">
							<tr>
								<td class="cmsMenuDivider defcursor"><<</td>
								<td class="cmsMenuTab cmsMenuTab-back" onclick="javascript: window.location='filestable.php?game=<?=$CMS_game?>&page=<?=$_GET['sby']?>';">НАЗАД</td>
								<td class="cmsMenuDivider defcursor">||</td>
								<td class="cmsMenuTab" onclick="javascript:toggle2('pages001'); toggle3('transes001'); toggle3('comments001');">Страници</td>
								<td class="cmsMenuDivider defcursor">||</td>
								<td class="cmsMenuTab" onclick="javascript:toggle2('transes001'); toggle3('pages001'); toggle3('comments001');">Преводи</td>
								<td class="cmsMenuDivider defcursor">||</td>
								<td class="cmsMenuTab" onclick="javascript:toggle2('comments001'); toggle3('pages001'); toggle3('transes001');">Бележки: <b class="cmsNumNotes textBLACK"> <?=$num_notes?> </b></td>
								<td class="cmsMenuDivider">>></td>
							</tr>
						</table>
					</center>
	<?php
	//---------------------------- SECOND MENU END ------------------------------------
	
		//---> Alpha-pager (Page list)
			$_GET['go']= isset($_GET['go']) ? cleanse($_GET['go']) : "";
			$_POST['editoract']= isset($_POST['editoract']) ? cleanse($_POST['editoract']) : "";
			$tmp= ($_GET['go']!="pending" AND $_POST['editoract'] != "yes") ? "block" : "none";
			echo "<div id='pages001' style='display:$tmp'>";
			$all_pages_array = array(); $pages_array = array();
			$pages_status= CMS_gamePagerOverall_Load();
			for($i=1;$i<=$CMS_pages;$i++){ 
				if (!isset($pages_status[$i])) $pages_status[$i]="red";
				if ($i==$CMS_page) { $brdrWHITE = "borderWHITE"; } else $brdrWHITE="";
				$pages_array[] = "button text".strtoupper($pages_status[$i])." $brdrWHITE";
			}
			$per = 0;
			if ($CMS_pages>999) {$TDwitdh="35px";$cons=18;} elseif ($CMS_pages>99) {$TDwitdh="25px";$cons=20;} else {$TDwitdh="15px";$cons=25;}; // Набързо скалъпвам широчината и броя на колоните в pager-а, съобразно броя на страниците, за да са с еднаква ширина бутоните в него
			echo "<table style='text-align:center; border-collapse:separate;'><tr>";
			for($i=1;$i<=$CMS_pages;$i++){
				if($per%$cons == 0){
					echo "</tr>";
				}
				if($per%$cons == 0){
					echo "<tr>";
				}
				$a= $i-1; $TDcolor= $pages_array[$a];
				echo <<<HTML
						<td class='$TDcolor unselectable' style='width:$TDwitdh;'
						onclick="javascript: window.location.href='$location?game=$CMS_game&name=$CMS_file&page=$i&sby=$_GET[sby]$addtoURL';">$i</td>
HTML;
				$per++;
			}
			echo "</table>";
			echo "</div>";
			
			$tmp= (isset($_GET['go']) && $_GET['go']==="pending") || (isset($_POST['editoract']) && $_POST['editoract']==="yes") ? "block" : "none";
			echo "<div id='transes001' style='display:$tmp'>";
		
		//---> Show all recorded translation for that text in that page
			$tq= $db->prepare("SELECT * FROM $translations_table WHERE file_name=:FILE and page=:PAGE ORDER BY id DESC");
			$tq->execute(array(":FILE"=>$CMS_file,":PAGE"=>$CMS_page));
			foreach($tq->fetchAll(PDO::FETCH_ASSOC) as $array_translations){
				$exploded= explode("\n", $array_translations['translation']);
				foreach ($exploded as $val) {
					$val_temp= explode("=>", $val);
					isset($val_temp[1]) || $val_temp[1]="";
					$userSEE[$val_temp[0]]['approved']=$val_temp[1];
				}
				unset($exploded);
				if ($array_translations['original']!=null){
					$exploded= explode("\n", $array_translations['original']);
					foreach ($exploded as $val) {
						$val_temp= explode("=>", $val);
						isset($val_temp[1]) || $val_temp[1]="";
						$userSEE[$val_temp[0]]['original']=$val_temp[1];
					}
					unset($exploded);
				}
				if($user_rights["ADD"]===1 && $user_rights["APPROVE"]!==1){
					$status= $array_translations['status'];
					if($status === 'Одобрен'){ $status_color = "GREEN"; } elseif($status === 'Неодобрен'){ $status_color = "RED"; } else { $status_color = "YELLOW"; }
					echo <<<TRANSLATION_BOX_FOR_USERS
							<table>
								<tr>
									<td>
										<div class='apview-border border$status_color' id=$array_translations[id]>
											<div class='forumheader'>
												<a href=/user.php?id.$array_translations[translator_id] name=$array_translations[id]>$array_translations[translator_name]</a>
												<span class='smalltext' style='float: right;'>$array_translations[time]</span>
											</div>
TRANSLATION_BOX_FOR_USERS;
					foreach($userSEE as $k=>$val) {
						$key = array_search("$k", $arrs["echoid"], true);
						$val["approved"]= cleanhtmlspecialchars($val["approved"]);
						$val["original"]= cleanhtmlspecialchars($val["original"]);
						$val["english"] = cleanhtmlspecialchars($arrs["en"][$key]);
						if ((trim($val['approved'])==trim($val['original']) OR !isset($val['original'])) AND ($val['approved']!=null)) {
							echo <<<ROW_APPROVED_AS_IT_IS
											<div class='forumheader3' style='padding:2px 4px;'>
												<span class='trapp'>$val[approved]</span>
											</div>
ROW_APPROVED_AS_IT_IS;
						}
						elseif($val['approved']!=null) {
							echo <<<ROW_APPROVED_BUT_CHANGED
											<div class='forumheader3' style='padding:2px 4px;'>
												<span class='trcyr'>$val[approved]</span><br>
												<span class='trsent'>$val[original]</span><br>
												<span class='trlat'>$val[english]</span><br>
											</div>
ROW_APPROVED_BUT_CHANGED;
						}
					}
					$status = $array_translations['status'];
					echo <<<CLOSING_USERS_TRANSLATION_BOX
											<center class='forumheader text$status_color'>$status</center>
										</div>
									</td>
								</tr>
							</table>
CLOSING_USERS_TRANSLATION_BOX;
				}
			
		//---> Show translsation areas for admin + Approve/disapprove/delete translations
				if($user_rights["APPROVE"]===1){
					$tran = ''; $pretran = '';
					$status = $array_translations['status'];
					$waiting_text = trim($array_translations['translation']);
						$waiting_rows = explode("\n", trim($waiting_text));
						foreach ($waiting_rows as $nextrow) {
							$exploded = explode("=>", $nextrow);
							$waiting_id[] = $exploded[0];
						}
						foreach ($waiting_id as $k=>$v) {
							$key = array_search($v, $arrs["echoid"], true);
							if($key===false) {
								$v_temp= $v."_IGcoLLen";
								$key= array_search($v_temp, $arrs["echoid"], true);
								if($key===false) {
									$v_temp.="_IGcoLLen";
									$key= array_search($v, $arrs["echoid"], true);
								}
								if($key!==false) {
									$nextrow_textid_exceptions[$v]= $v_temp;
									$v= $v_temp;
								}
							}
							$pretran .= "<span class='textYELLOW'>".$arrs["echoid"][$key]."=</span>".$arrs["content"][$key]."<br>";
							$waiting_id_text[$k]['id']= $arrs["echoid"][$key];
							if($key!==false) {
								$waiting_id_text[$k]['en']= $arrs["en"][$key];
							} else $waiting_id_text[$k]['en']='Репликата не фигурира на тази страница.';
							if (isset($arr_temp_green) AND in_array($arrs["echoid"][$key],$arr_temp_green) AND $key!==false){
								$waiting_id_text[$k]['bg']= $arrs["bg"][$key]."<br>";
								if(isset($v_temp)) $waiting_id_text[$k]['bg']="(Репликата е оставена на английски.) ".$waiting_id_text[$k]['bg'];
							} else $waiting_id_text[$k]['bg']='';
							unset($v_temp,$k,$key);
						}
					if($status == 'Одобрен'){ $status_color = "GREEN"; } elseif($status == 'Неодобрен'){ $status_color = "RED"; } else { $status_color = "YELLOW"; }
					echo "<table><tr><td>";
					echo "<div class='apview-border border$status_color' id='".$array_translations['id']."'>";
					echo "<div class='forumheader'><a href=/user.php?id.".$array_translations['translator_id'].">".$array_translations['translator_name']."</a> <span class='smalltext' style='float: right;'>".$array_translations['time']."</span></div>";
					echo '<form action="" method="post">';
					if($status == 'В процес на проверка...') {
						$rows_in_thistranslation= count($waiting_rows);
						foreach ($waiting_rows as $rownum=>$rowbody) {
							$nextrow= explode("=>", $rowbody);
							$nextrow[1]= cleanhtmlspecialchars($nextrow[1]);
							echo "<textarea id='r_$array_translations[id]$rownum' name='r_$array_translations[id]$rownum' class='expand tbox borderGREY TBOX2' style='width:93%; margin:0px;' onChange='approve_shananigans_exec(\"$array_translations[id]\",\"r_$array_translations[id]$rownum\",\"r_$array_translations[id]{$rownum}_t\",\"$rows_in_thistranslation\");' onKeyUp='approve_shananigans_exec(\"$array_translations[id]\",\"r_$array_translations[id]$rownum\",\"r_$array_translations[id]{$rownum}_t\",\"$rows_in_thistranslation\");'>$nextrow[1]</textarea><div style='float:right; '><input id='ord_$array_translations[id]_$rownum' name='ord_$array_translations[id]_$rownum' type='text' pattern='[1-5]{1}' title='От 1 до 5' size='1' value='1' class='button textGREY' style='padding:1px 2px;'/><span class='button textRED' onClick='clearTextArea(\"r_$array_translations[id]$rownum\");populateTextArea(\"UFORM_$array_translations[id]\",\"r_$array_translations[id]\",\"trans_$array_translations[id]\");'>X</span></div>";
							echo "<div style='opacity:0.7; margin-top:-2px; margin-bottom:4px; margin-left:4px;' onmouseup=\"parseselection();\"><div class='trcyr'>{$waiting_id_text[$rownum]['bg']}</div><div class='trlat'>{$waiting_id_text[$rownum]['en']}</div>";
							if ($nextrow[0]!=null) { 
								$addarrow="=>";
								if(isset($nextrow_textid_exceptions[$nextrow[0]])) $nextrow[0]= $nextrow_textid_exceptions[$nextrow[0]];
								$nextrow[0]= cleanhtmlspecialchars($nextrow[0]);
							}
							echo "<div style='float:right;'><textarea title='$nextrow[0]/".$waiting_id_text[$rownum]['id']."' type='text' id='r_$array_translations[id]$rownum-tag' name='r_$array_translations[id]$rownum-tag' class='expand16-1 tbox borderGREY TBOX2' style='margin:0px;width:75px;vertical-align:top;opacity:0.5;'>$nextrow[0]$addarrow</textarea></div>";
							echo "</div>";
						}
					}
						unset ($waiting_rows, $exploded, $waiting_id);
						if($status == 'Одобрен'){ 
							foreach($userSEE as $k=>$val) {
								$val["approved"]= cleanhtmlspecialchars($val["approved"]);
								if(!isset($val['approved'])) $val['approved']="";
								$val["original"]= cleanhtmlspecialchars($val["original"]);
								if (trim($val['approved'])==trim($val['original']) OR $val['original']==null) {
									echo "<div class='forumheader3' style='padding:2px 4px;'>";
									echo "<span class='trapp'>$val[approved]</span>";
									echo "</div>";
								}
								elseif (empty($val['approved']) and empty($val['original'])) {}
								else {
									if (empty($val['approved']) and !empty($val['original'])) {$val['approved']="<изтрито>";}
									$key = array_search("$k", $arrs["echoid"], true);
									$val["english"] = cleanhtmlspecialchars($arrs["en"][$key]);
									echo "<div class='forumheader3' style='padding:2px 4px;'>";
									echo "<span class='trcyr'>$val[approved]</span><br>";
									echo "<span class='trsent'>$val[original]</span><br>";
									echo "<span class='trlat'>$val[english]</span><br>";
									echo "</div>";
								}
							}
						} elseif($status == 'Неодобрен'){
							foreach($userSEE as $k=>$val) {
								$val["approved"]= cleanhtmlspecialchars($val["approved"]);
								$val["original"]= cleanhtmlspecialchars($val["original"]);
								$key = array_search("$k", $arrs["echoid"], true);
								$val["english"] = cleanhtmlspecialchars($arrs["en"][$key]);
								if(!empty($val['original'])) {
									echo "<div class='forumheader3' style='padding:2px 4px;'>";
									echo "<span class='textYELLOW'>$val[original]</span><br>";
									echo "<span class='textRED'>$val[english]</span><br>";
									echo "</div>";
								}
							}
						}
						if(is_array($nextrow_textid_exceptions)) {
							foreach($nextrow_textid_exceptions as $id_old=>$id_changed) {
								$waiting_text= str_replace("\n".$id_old."=>","\n".$id_changed."=>",$waiting_text);
							}
						}
						$waiting_text= cleanhtmlspecialchars($waiting_text);
						if ( isset($_GET['go']) AND $_GET['go']=="pending" ) {
							echo '<textarea name="trans_'.$array_translations['id'].'" id="trans_'.$array_translations['id'].'" class="expand tbox borderGREY TBOX2" style="width:99%;opacity:0.4;display:none;">'.$waiting_text.'</textarea>';
						}
						else {
							echo '<textarea name="trans_'.$array_translations['id'].'" id="trans_'.$array_translations['id'].'" class="expand tbox borderGREY TBOX2" style="width:99%;opacity:0.4;display:none;">'.$waiting_text.'</textarea>';
						}
/*				echo '<div class="forumheader"><a class="textGREY"><u>Настоящо състояние на репликите</u>: </a>(<a href="javascript:toggle(\'tip_'.$array_translations['id'].'\');">Покажи</a>)';
				echo '<div id="tip_'.$array_translations['id'].'" style="display: none; font-weight:normal;">';
				echo $pretran;
				echo '</div></div>'; */
				echo "<center class='forumheader' style='height:5px;'></center>";
				echo "<center class='forumheader3 text$status_color'>".$status."</center>";
				echo '<center class="forumheader" ><input type="hidden" name="editoract" value="yes">';
				if($status == 'Одобрен'){
					echo '<input name="approve_'.$array_translations['id'].'" type="submit" value="Одобри" style="text-decoration: line-through;" class="button" disabled>';
					echo '<input name="disapprove_'.$array_translations['id'].'" type="submit" value="Отхвърли" style="text-decoration: line-through;" class="button" disabled>';
				}
				elseif($status == 'Неодобрен'){
					echo '<input name="approve_'.$array_translations['id'].'" type="submit" value="Одобри" class="button">';
					echo '<input name="disapprove_'.$array_translations['id'].'" type="submit" value="Отхвърли" style="text-decoration: line-through;" class="button" disabled>';
				}
				else{
					echo '<a href="../../plugins/pm/pm.php?send.'.$array_translations['translator_id'].'" target="_blank" title="Изпрати лично съобщение. (Отваря нов таб.)"><img src="../../plugins/pm/images/pm.png" alt="Лични съобщения" class="button buttonBLACK" style="vertical-align:bottom;"></a>';
					echo '<input name="approve_'.$array_translations['id'].'" type="submit" value="Одобри" class="button buttonGREEN">';
					echo '<input name="change_'.$array_translations['id'].'" type="submit" value="Редактирай" class="button buttonYELLOW">';
					echo '<input name="disapprove_'.$array_translations['id'].'" type="submit" value="Отхвърли" class="button buttonRED">';
				}
				echo '<input name="delete_'.$array_translations['id'].'" type="submit" value="Изтрий" class="button buttonBLACK" />';
				if($status == 'В процес на проверка...') echo '<input name="split_'.$array_translations['id'].'" type="submit" value="Разбий" class="button buttonBLACK" /></center>';
				
				echo "<input type='hidden' name='sbmtchck' value='true'>";
				
				echo '</form>';
				echo "</div>";
				echo "</td>";
				echo "</tr>";
				echo "</table>";
			}
			unset($userSEE);
		}
	echo "</div>";

	if(isset($_POST['comsubmit'])) { echo "<div id='comments001' style='display:block'>"; }
	else { echo "<div id='comments001' style='display:none'>"; }
				if (isset($_POST['comment'])) {
					$posteded = strtoupper($_POST['comment']); 
					$posteded = strip_tags($posteded); 
					$posteded = trim ($posteded);
				}	

				$temp=0;
				$notes= mysql_query("SELECT * FROM cms_notes WHERE game = '".mysql_real_escape_string($CMS_game)."' AND status = 'Видимо' ORDER by time DESC");
				while($row=mysql_fetch_assoc($notes)) {
					$arr_notes[$temp]=$row;
					$temp++;
				}
				
				if ($temp == 0) { echo "<center><span class='textRED' style='font-size:150%; vertical-align:bottom;'>✆</span> <span class='textBLUE' style='font-weight:bold;'><u>Все още няма добавени бележки.</u></span></center>"; }
				echo "<div class='textWHITE' id='notes_container'>";
				$temp=1;
				if(isset($arr_notes)) {
					foreach ($arr_notes as $key => $note) {
						$note['time']= months_inBG(date("j F : H:i", strtotime($note['time'])));
						$class2= in_array($note['user_name'],$adminss) ? "cmntUser1" : "cmntUser2";
						if (USERNAME===$note['user_name']||$user_rights["APPROVE"]===1) {
							$add_buttons_to_note=<<<ADD_BUTTONS_FOR_EACH_NOTE
								<button type='button' class='unselectable button textRED'   id='note$note[id]_X' style='padding:0px; padding-top:2px; min-width:18px;' title='Изтриване' onclick='delete_note_from_notes_table($note[id]);'>X</button>
								<button type='button' class='unselectable button textWHITE' id='note$note[id]_E1' style='padding:0px; padding-top:2px; min-width:18px;' title='Редакция' onclick='toggle_hidden_note_textarea($note[id])'><img src='icons/edit_icon2.png' alt='EDIT' height='11'></button>
ADD_BUTTONS_FOR_EACH_NOTE;
							$add_hidden_fields_to_note=<<<ADD_HIDDEN_FIELDS_FOR_EACH_NOTE
								<div id='note$note[id]_editarea' style='display:none;'>
									<textarea id='note$note[id]_editfield' class='expand tbox borderGREY TBOX2' style='width:93%;'></textarea>
									<button type='button' class='unselectable button textWHITE' id='note$note[id]_E2' style='vertical-align:top; padding:0px; 	font-size:10px; font-weight:normal;' onclick='post_hidden_note_textarea($note[id]);'>Запази</button>
								</div>
ADD_HIDDEN_FIELDS_FOR_EACH_NOTE;
						} else {
							$add_buttons_to_note="";
							$add_hidden_fields_to_note="";
						}
						echo <<<NOTE
							<div class='forumheader3'>
								<div class='forumheader'>
									$add_buttons_to_note<span class='$class2'> $note[user_name]</span> <span class='cmntDate'>$note[time]</span>
								</div>
								<div class='unselectable' style='padding-left:5px;' id='note$note[id]_content'>$note[note]</div>
								$add_hidden_fields_to_note
								<center id="note$note[id]_status" style="font-weight:bold;"></center>
							</div>
NOTE;
						$add_buttons_to_note="";
						$temp++;
					}
				}
				echo "</div>";
				echo "<div class='forumheader3'>
						<center id='note_add_new_status' class='textWHITE' style='padding:5px;'></center>
						<center style='padding-top:5px;'>
							<textarea name='comment' cols='90' class='expand tbox borderGREY TBOX2' id='note_add_new'>Вашият коментар...</textarea>
						</center>
						<center>
							<button type='button' class='unselectable button textWHITE' onclick='note_add_new($note[id])'>Добави</button>
						</center>
					  </div>";
	echo "</div>";

	$translationButtons= "";
	if($user_rights["APPROVE"]===1){
		$pendings= CMS_pendingTranslationsLoad("for game");
		if (!isset($_GET['pendingID'])) {
			$filestart= array_search($CMS_file, $pendings);
			foreach ($pendings as $index => $pending) {
				if ($pending['page']<$CMS_page AND $pending['file_name']==$CMS_file) {$prev_key= $index;}
				elseif ($pending['page']>=$CMS_page AND $pending['file_name']==$CMS_file) {$next_key= $index; break;}
				else {
						$temp= $filestart-1;
						if (isset($pendings[$temp])) { $prev_key= $temp; }
						$temp= $filestart+1;
						if (isset($pendings[$temp])) { $next_key= $temp; }
				}
			}
		}
		else {
			$present= $_GET['pendingID'];
			$temp= $present-1;
			if (isset($pendings[$temp])) { $prev_key= $temp; }
			$temp= $present+1;
			if (isset($pendings[$temp])) { $next_key= $temp; }
		}
		if (isset($prev_key)) {
			$tmp_name= $pendings[$prev_key]['file_name']; $tmp_page= $pendings[$prev_key]['page']; $tmp_id= $pendings[$prev_key]['id'];
			$prev="$location?game=$CMS_game&name=$tmp_name&page=$tmp_page&pendingID=$prev_key&go=pending&sby=$_GET[sby]$addtoURL#$tmp_id";
		}
		if (isset($next_key)) {
			$tmp_name= $pendings[$next_key]['file_name']; $tmp_page= $pendings[$next_key]['page']; $tmp_id= $pendings[$next_key]['id'];
			$next="$location?game=$CMS_game&name=$tmp_name&page=$tmp_page&pendingID=$next_key&go=pending&sby=$_GET[sby]$addtoURL#$tmp_id";
		}
		if (isset($prev)) {$translationButtons.="<a href='$prev' style='vertical-align:middle;' id='prev-trans'>◄</a>";}
		if($pendings['count']==0){$tclass='textBLACK';} else $tclass='textDBLUE';
		$translationButtons.="<span class='$tclass' style='vertical-align:middle; font-weight:bold;'>".$pendings['count']."</span>";
		if (isset($next)) {$translationButtons.="<a href='$next' style='vertical-align:middle;' id='next-trans'>►</a>";}
		//$translationButtons= "<button title='Всички преводи' class='cmsBottomButton' onClick=window.open('apall.php?game=$CMS_game')><img src='icons/bottom-approve.png' HEIGHT='14px' WIDTH='14px'></button>".$translationButtons;
	}

	$youtubesrc= urlencode($gamename);	
	echo <<<HTML
				<center class='cmsBottomBar forumheader'>
						<form name="redirectSearch" method="post" action="redirect.php" target="_blank" style="display: inline;">
						<input type="text" name="keyword" id="keyword" class="cmsTextarea2 borderGREY" style="vertical-align:bottom;"/>
						<button title="Потърси в речник" type="submit" name="direction_dir-bg" id="srch-dict" class="cmsBottomButton" value="sent"><img src="icons/bottom-dirbg.png" HEIGHT='14px' WIDTH='14px'></button><button title="Потърси в Urban Dictionary" type="submit" name="direction_urbandict" id="srch-urban" class="cmsBottomButton" value="sent"><img src="icons/bottom-urbandict.png" HEIGHT='14px' WIDTH='14px'></button><button title="Потърси с Google" type="submit" name="direction_google" id="srch-ggle" class="cmsBottomButton" value="sent"><img src="icons/bottom-google.png" HEIGHT='14px' WIDTH='14px'></button><button title="Потърси в Уикипедия" type="submit" name="direction_wiki" id="srch-wiki" class="cmsBottomButton" value="sent"><img src="icons/bottom-wikipedia.png" HEIGHT='14px' WIDTH='14px'></button><button type="submit" title="Преведи с Google Translate" name="direction_gtranslate" id="srch-gtr" class="cmsBottomButton" value="sent"><img src="icons/bottom-gtranslate.png" HEIGHT='14px' WIDTH='14px'></button><button type="submit" title="Английски тълковен речник" name="direction_thefreedict" id="srch-tfd" class="cmsBottomButton" value="sent"><img src="icons/bottom-thefreedict.png" HEIGHT='14px' WIDTH='14px'></button><button type="submit" title="Речник на българския език" name="direction_chitankadict" id="srch-chi" class="cmsBottomButton" value="sent"><img src="icons/bottom-chitankadict.png" HEIGHT='14px' WIDTH='14px'></button>
						</form>
						<span class='unselectable textBLACK'>||</span>
						$translationButtons
						<span class='unselectable textBLACK'>|| </span>
						<button title='YouTube помагало' class='cmsBottomButton' onClick=window.open('http://www.youtube.com/results?search_query=$youtubesrc+walkthrough')><img src='icons/bottom-youtube.bmp' HEIGHT='14px'></button>
					</center>
HTML;
	if($user_rights["APPROVE"]===1){
		echo "		<div class='cmsRightBar' style='margin-bottom: 150px;'>";
		for($ictrl=1;$ictrl<=9;$ictrl++){
			if (isset($_COOKIE['playon-ctrls'][$ictrl])) { $ctrl_value= $_COOKIE['playon-ctrls'][$ictrl]; } else $ctrl_value= "";
			echo "		<button disabled='disabled' id='CTRL$ictrl' class='button' style='cursor:help !important;' title='Ctrl+$ictrl\nНатискането на комбинцията, докато попълвате превод, въвежда съдържанието на полето след това квадратче в полето, където пишете.'>$ictrl</button>
						<input type='text' name='CTRL$ictrl-text' id='CTRL$ictrl-text' class='cmsTextarea2' style='width:60px;' value='$ctrl_value'/>
						<br>";
		} echo "	<button id='savectrls' class='button'>Запази</button>
					<div id='savectrls-message'></div>
					</div>";	
	}
	if($user_rights["APPROVE"]===1){
		echo <<<HTML
					<div class='cmsRightBar' style='margin-bottom: 50px;'>
					<button disabled='disabled' class='button' style='cursor:help !important;' title='Дума на английски\nЗадължителна, за да се започне изпращането.'>EN</button>
					<input type='text' id='wordEN' name='wordEN' class='cmsTextarea2' style='width:50px;'/>
					<button disabled='disabled' class='button' style='cursor:help !important;' title='Превод на български\nЗадължителен, за да се започне изпращането.'>BG</button>
					<input type='text' id='wordBG' name='wordBG' class='cmsTextarea2' style='width:50px;'/>
					<button id='savedict' class='button'>Въведи</button>
					<div id='savedict-message'></div>
					</div>
HTML;
	}

	}else{
		echo "<center class='textRED'>Само регистрирани потребители могат да се включат в превода</center><div>";
	}
	echo "</div></div><div class='forumheader2'></div>";
	require_once("viewtext-java.php");
}
ramka("close");
$text= null;
require_once(FOOTERF);

}else {
	echo "<div class='forumheader'>Не е уточнена игра, която да бъде показана, играта е преведена, или нямате достъп до нея. Извиняваме се за неудобството.</div>";
	ramka("close");
	require_once(FOOTERF);
}
?>